package cn.appsys.controller.dev;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.pojo.Page;
import cn.appsys.service.AppCategoryService;
import cn.appsys.service.AppInfoService;
import cn.appsys.service.AppVersionService;
import cn.appsys.service.DataDictionaryService;

@Controller
@RequestMapping("/dev/flatform/app")
public class AppInfoController {

	@Autowired
	AppInfoService appInfoService;

	@Autowired
	DataDictionaryService dataDictionaryService;

	@Autowired
	AppCategoryService appCategoryService;

	@Autowired
	AppVersionService appVersionService;

	@RequestMapping("/list")
	public String list(AppInfo appInfo, @RequestParam(defaultValue = "1", required = false) Integer pageIndex,
			Model model) {
		Page<AppInfo> pageInfo = appInfoService.selectAppInfoByPage(appInfo, pageIndex);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("a", appInfo);

		//
		model.addAttribute("statusList", dataDictionaryService.selectDataDictionary("APP_STATUS"));
		model.addAttribute("flatFormList", dataDictionaryService.selectDataDictionary("APP_FLATFORM"));
		model.addAttribute("categoryLevel1List", appCategoryService.selectAppCategory(0L));
		// 初始化选中二级以及三级
		if (appInfo.getCategoryLevel1() != null && appInfo.getCategoryLevel1() > 0)
			model.addAttribute("categoryLevel2List", appCategoryService.selectAppCategory(appInfo.getCategoryLevel1()));
		if (appInfo.getCategoryLevel2() != null && appInfo.getCategoryLevel2() > 0)
			model.addAttribute("categoryLevel3List", appCategoryService.selectAppCategory(appInfo.getCategoryLevel2()));
		return "developer/appinfolist";
	}

	@RequestMapping("/appinfoadd")
	public String appinfoadd(Model model) {
		return "developer/appinfoadd";
	}

	@RequestMapping("/appinfoaddsave")
	public String appinfoaddsave(AppInfo appInfo, MultipartFile a_logoPicPath, Model model, HttpSession httpSession) {
		// 保存图片
		if (!a_logoPicPath.isEmpty()) {
			try {
				// 新文件名
				String fileName = System.currentTimeMillis() + "_logo."
						+ FilenameUtils.getExtension(a_logoPicPath.getOriginalFilename());
				File file = new File("E:\\uploadfiles\\" + fileName);
				a_logoPicPath.transferTo(file);

				appInfo.setLogoPicPath("/AppInfoSystem/showImg?fileName=" + fileName);// url路径
																						// 访问路径
				appInfo.setLogoLocPath(file.getAbsolutePath());// 绝对路径
			} catch (Exception e) {
				e.printStackTrace();
				model.addAttribute("fileUploadError", "logo上传失败");
				return "developer/appinfoadd";
			}
		} else {
			model.addAttribute("fileUploadError", "logo不能为空");
			return "developer/appinfoadd";
		}
		// 添加
		DevUser devUser = (DevUser) httpSession.getAttribute("devUserSession");
		// 设置开发者id
		appInfo.setDevId(devUser.getId());
		appInfo.setCreatedBy(devUser.getId());
		boolean f = appInfoService.addAppInfo(appInfo);
		if (f) {
			return "redirect:list";
		}

		model.addAttribute("error", "添加失败");
		return "developer/appinfoadd";
	}

	@RequestMapping("/appinfomodify")
	public String appinfomodify(Long id, Model model) {
		model.addAttribute("appInfo", appInfoService.getAppInfoById(id));
		return "developer/appinfomodify";
	}

	@RequestMapping("/appversionadd")
	public String appversionadd(Long id, Model model) {
		// 历史版本列表
		model.addAttribute("appVersionList", appVersionService.selectAppVersionList(id));
		model.addAttribute("appId", id);
		return "developer/appversionadd";
	}

	// 保存版本
	@RequestMapping("/addversionsave")
	public String addversionsave(AppVersion appVersion, MultipartFile a_downloadLink, Model model,
			HttpSession session) {
		if (!a_downloadLink.isEmpty()) {
			try {
				// 新文件名
				String fileName = System.currentTimeMillis() + "_apk."
						+ FilenameUtils.getExtension(a_downloadLink.getOriginalFilename());
				File file = new File("E:\\uploadfiles\\" + fileName);
				a_downloadLink.transferTo(file);

				appVersion.setDownloadLink("/AppInfoSystem/download?fileName=" + fileName);// 下载路径
				appVersion.setApkLocPath(file.getAbsolutePath());// 绝对路径
				appVersion.setApkFileName(a_downloadLink.getOriginalFilename());// 原名
			} catch (Exception e) {
				e.printStackTrace();
				model.addAttribute("appVersionList", appVersionService.selectAppVersionList(appVersion.getAppId()));
				model.addAttribute("appId", appVersion.getAppId());
				model.addAttribute("fileUploadError", "logo上传失败");
				return "developer/appversionadd";
			}
		} else {
			model.addAttribute("appVersionList", appVersionService.selectAppVersionList(appVersion.getAppId()));
			model.addAttribute("appId", appVersion.getAppId());
			model.addAttribute("fileUploadError", "logo不能为空");
			return "developer/appversionadd";
		}
		// 添加
		DevUser devUser = (DevUser) session.getAttribute("devUserSession");
		appVersion.setCreatedBy(devUser.getId());

		boolean f = appVersionService.addAppVersion(appVersion);
		if (f) {
			return "redirect:list";
		}
		model.addAttribute("appVersionList", appVersionService.selectAppVersionList(appVersion.getAppId()));
		model.addAttribute("appId", appVersion.getAppId());
		model.addAttribute("error", "添加失败");
		return "developer/appversionadd";
	}

	@RequestMapping("/appview/{id}")
	public String appview(@PathVariable Long id, Model model) {
		model.addAttribute("appInfo", appInfoService.getAppInfoById(id));
		model.addAttribute("appVersionList", appVersionService.selectAppVersionList(id));
		return "developer/appinfoview";
	}

	@ResponseBody
	@RequestMapping("/delapp")
	public Map<String, Object> delapp(Long id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean f = appInfoService.deleteAppInfo(id);
		resultMap.put("delResult", f ? "true" : "false");
		return resultMap;
	}

	// 58/sale
	@ResponseBody
	@RequestMapping("/{id}/sale")
	public Map<String, Object> sale(@PathVariable Long id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		AppInfo appinfo = appInfoService.getAppInfoById(id);
		boolean f = false;
		if (appinfo.getStatus() == 5 || appinfo.getStatus() == 2) {
			// 上架
			f = appInfoService.updateStatus(id, 4);
		} else if (appinfo.getStatus() == 4) {
			// 下架
			f = appInfoService.updateStatus(id, 5);
		}
		resultMap.put("errorCode", "0");
		resultMap.put("resultMsg", f ? "success" : "failed");
		return resultMap;
	}

	// 检查APKName是否存在
	@ResponseBody
	@RequestMapping("/apkexist")
	public Map<String, Object> apkexist(String APKName) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isEmpty(APKName)) {
			map.put("APKName", "empty");
		} else {
			boolean f = appInfoService.apkexist(APKName);
			// 存在
			map.put("APKName", f ? "exist" : "noexist");
		}
		return map;
	}

	// 加载分类
	@ResponseBody
	@RequestMapping("/categorylevellist")
	public List<AppCategory> categorylevellist(Long pid) {
		return appCategoryService.selectAppCategory(pid);
	}

	@ResponseBody
	@RequestMapping("/datadictionarylist")
	public List<DataDictionary> datadictionarylist() {
		return dataDictionaryService.selectDataDictionary("APP_FLATFORM");
	}

}
